﻿using Common.Logging;
using Infrastructure.Lib.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebServiceCapture.Job
{
    public class FloodWebSite
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(FloodWebSite));

        private WebserviceClient _client;

        private string _savePath;

        private string[] _exitsJpgs;

        private IEnumerable<dynamic> _dowloadHttpUrls = null;

        public FloodWebSite SetParameter<T>(T p)
        {
            if (p.GetType().IsAssignableFrom(typeof(WebserviceClient)))
            {
                _client = p as WebserviceClient;
            }
            else
            {
                _savePath = Convert.ToString(p);
            }
            return this;
        }

        public FloodWebSite Initialize()
        {
            return Initialize(_savePath, _client);
        }

        private FloodWebSite Initialize(string savePath, WebserviceClient client)
        {
            _client = client;
            _savePath = savePath;

            if (!FileHelper.IsExistDirectory(savePath))
            {
                FileHelper.CreateDirectory(savePath);
            }

            _exitsJpgs = FileHelper.GetFileNames(_savePath);

            //获取接口列表数据
            _dowloadHttpUrls = _client.CombineParamter()
                 .Invoke("getOneStationImgInfos")
                 .Select(d => new
                 {
                     Time = d.Time,
                     SavePath = Path.Combine((string)_savePath, (string)d.Name),
                     Url = string.Format("{0}{1}"
                         , client.Model.Url.ToLower().Replace(@"holdfujianservices.asmx", "")
                         , ((string)d.Url).ToLower().Replace(@"../", ""))
                 })
                 .ToList()
                 .FindAll(d => !((IList)_exitsJpgs).Contains(d.SavePath))
                 .OrderBy(d => d.Time)
                 .Distinct();

            return this;
        }

        public void SaveNotDownloadJpg()
        {
            if (_dowloadHttpUrls == null || _dowloadHttpUrls.Count() == 0)
                return;

            _dowloadHttpUrls.ForEach(d =>
            {
                if (FileHelper.FileIsUsed(d.SavePath)) return;

                HttpHelper.Download(d.Url, d.SavePath);
                //修改文件的修改时间
                FileInfo file = new FileInfo(d.SavePath);
                file.LastWriteTime = Convert.ToDateTime(d.Time);
            });
        }

    }
}
